package cn.tsingyu.antsclub.controller;

import cn.tsingyu.antsclub.common.Json;
import cn.tsingyu.antsclub.model.Account;
import cn.tsingyu.antsclub.model.Trade;
import cn.tsingyu.antsclub.model.User;

import com.jfinal.core.Controller;

public class UserController extends Controller {
	public void register(){
		String uname = getPara("uname").trim();
		String pwd = getPara("pwd").trim();
		String nickname = getPara("nickname");
		String email = getPara("email");
		Json j = new Json();
		try{
			if(User.dao.register(uname,pwd,nickname,email)){
				String msg = "恭喜哈，注册成功了，";
				User user = User.dao.login(uname, pwd);
			    if(user!=null) {
			    	j.setSuccess(true);
			    	msg+="登录也成功了，";
			    	if(Account.dao.createNewAccount(user.getInt("id"),uname)){
			    		msg+="账户也创建成功了，现在为您跳转到首页";
			    	}else{
			    		msg+="账户创建没成功，现在为您跳转到首页";
			    	}
			    	j.setObj(user);
					setSessionAttr("uname", uname);
					setSessionAttr("uid",user.get("id"));
			    }else{
			    	j.setSuccess(false);
			    	msg+="登录失败了，现在为您跳转到登录页";
			    }
			    j.setMsg(msg);
			}else{
				j.setSuccess(false);
				j.setMsg("糟糕，注册失败了");
			}
		}catch(Exception e){
			String exceptionMsg=e.getMessage();
			e.printStackTrace();
			if(exceptionMsg.contains("uname") && exceptionMsg.contains("Duplicate")){
				j.setSuccess(false);
				j.setMsg("糟糕，用户名:"+uname+" 被别人抢啦，换一个试试吧");
			}else if(exceptionMsg.contains("nickname") && exceptionMsg.contains("Duplicate")){
				j.setSuccess(false);
				j.setMsg("糟糕，昵称:"+uname+" 被别人抢啦，换一个试试吧");
			}else{
				j.setSuccess(false);
				j.setMsg("糟糕，注册失败了，详情原因请联系管理员");
			}
		}
		renderJson(j);
	}
	public void login(){
		String uname = getPara("uname").trim();
		String pwd = getPara("pwd").trim();
		User user = User.dao.login(uname, pwd);
		Json j = new Json();
	    if(user!=null) {
	    	j.setSuccess(true);
	    	j.setMsg("登录成功,现在为您跳转到首页");
	    	j.setObj(user);
			setSessionAttr("uname", uname);
			setSessionAttr("uid",user.get("id"));
	    }else{
	    	j.setSuccess(false);
	    	j.setMsg("登录失败,请检查您的用户名密码");
	    }
	    renderJson(j);
	}
	public void myAccount(){
		String uid = getPara("uid").trim();
		renderJson(Account.dao.findByUserId(uid));
	}
	public void myTrade(){
		String uid = getPara("uid").trim();
		renderJson(Trade.dao.myTrade(1,10,uid).getList());
	}
}
